package com.example.littleken.sqlitetext;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**本类封装了SQLite数据库的增删查改接口方法
 * Created by littleken on 2018/5/6.
 */
//在本类构造时获取SQLiteOpenHelper对象
public class SQLiteDao {
    private SQLiteDatabase db;

    public SQLiteDao(final Context context){
        SQLiteOpenHelper helper = new SQLiteOpenHelper(context,"test2.db",null,1) {
            @Override
            public void onCreate(SQLiteDatabase db) {
               // Toast.makeText(context,"数据库创建",Toast.LENGTH_SHORT).show();
                Log.e("TAG","数据库创建");

                String sql = "create table info_tb (_id integer primary key autoincrement," +
                        "name varhcar(20)," +
                        "age integer, "+
                        "gender varhcar(4) )";
                db.execSQL(sql);
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
               // Toast.makeText(context,"数据库升级",Toast.LENGTH_SHORT).show();
                Log.e("TAG","数据库升级");
            }
        };

        db = helper.getReadableDatabase();
    }

    public void insert(Student stu){
        String sql_insert = "insert into info_tb(name,age,gender) values(?,?,?)";
        Log.e("TAG",sql_insert);
        db.execSQL(sql_insert,new String[]{
                stu.getName(),stu.getAge()+"",stu.getGender()
        });
    }

    public Cursor select(String...strs){
    /*分两类，1，无条件查询，查询所有数据
              2，有条件查询，只查询符合条件数据
    * */
        String sql_select = "select * from info_tb";
        if(strs.length != 0){
            //有条件查询
            sql_select += " where " + strs[0] + "='" + strs[1] + "'";
        }
        Log.e("TAG",sql_select);
        Cursor c = db.rawQuery(sql_select,null);
        return c;
    }

    public void delete(String...strs){
        String sql_delete  = "delete from info_tb where " + strs[0] + "='" + strs[1] + "'";
        db.execSQL(sql_delete);
    }

    public void update(Student stu){
        String sql = "update info_tb set name=?,age=?,gender=? where _id=?";
        db.execSQL(sql,new Object[]{stu.getName(),stu.getAge(),stu.getGender(),stu.getId()});
    }
}
